package com.upsuns.multiop;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import com.upsuns.entity.FileEntity;
import com.upsuns.fileop.FileReaderThread;
import com.upsuns.fileop.FileWriterThread;
import com.upsuns.utils.Constants;

/**
 *@Description:<p>线程池实现</p>
 *@author 王旭
 *@time 2016-1-30 下午4:43:57
 */
public class ThreadBatch {
	
	private List<Runnable> threads;
	
	private FileEntity fe;
	
	public static CountDownLatch latch = new CountDownLatch(Constants.THREAD_NUM+1);
	
	
	public ThreadBatch(FileEntity fe) {
		if(Constants.TASK_TYPE == null) {
			System.out.println("任务类型不确定");
			return ;
		}
		
		this.fe = fe;
		
		threads = new ArrayList<Runnable>();
		
		if("SENT".equals(Constants.TASK_TYPE)) {
			for(int i=1; i<=Constants.THREAD_NUM; i++) {
				threads.add(new FileReaderThread(fe.getFile(),
						(i-1) * fe.getLenPerThread(), fe.getLenPerThread(), i));
			}
			threads.add(new FileReaderThread(fe.getFile(), 
					Constants.THREAD_NUM * fe.getLenPerThread(), fe.getLenRest(), Constants.THREAD_NUM+1));
		}
		
		else {
			for(int i=1; i<=Constants.THREAD_NUM; i++) {
				threads.add(new FileWriterThread(fe,
						(i-1) * fe.getLenPerThread(), fe.getLenPerThread(), i));
			}
			threads.add(new FileWriterThread(fe, 
					Constants.THREAD_NUM * fe.getLenPerThread(), fe.getLenRest(), Constants.THREAD_NUM+1));
		}
		
	}
	
	public void startAll() {
		for(Runnable r : threads) {
			new Thread(r).start();
		}
	}

	public List<Runnable> getThreads() {
		return threads;
	}

	public void setThreads(List<Runnable> threads) {
		this.threads = threads;
	}

	public FileEntity getFe() {
		return fe;
	}

	public void setFe(FileEntity fe) {
		this.fe = fe;
	}
	
}
